<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="优惠金额" prop="couponAmout">
        <el-input
          v-model="queryParams.couponAmout"
          placeholder="请输入优惠金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="满减金额" prop="fullAmount">
        <el-input
          v-model="queryParams.fullAmount"
          placeholder="请输入满减金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="发放开始时间" prop="grantStartTime">
        <el-date-picker clearable
          v-model="queryParams.grantStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发放开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="发放结束时间" prop="grantEndTime">
        <el-date-picker clearable
          v-model="queryParams.grantEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发放结束时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="生效时间" prop="effectiveStartTime">
        <el-date-picker clearable
          v-model="queryParams.effectiveStartTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择生效时间"
          :picker-options="startPickerOptionsQuery"
          default-time="00:00:00"
          >
      </el-date-picker>
      </el-form-item>
      <el-form-item label="失效时间" prop="effectiveEndTime">
        <el-date-picker clearable
          v-model="queryParams.effectiveEndTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择失效时间"
          :picker-options="endPickerOptionsQuery"
          default-time="17:30:00">
        </el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="发放数量" prop="quantity">
        <el-input
          v-model="queryParams.quantity"
          placeholder="请输入发放数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="每人可重复领取数量" prop="repeatQuantity">
        <el-input
          v-model="queryParams.repeatQuantity"
          placeholder="请输入每人可重复领取数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['coupontem:coupontem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['coupontem:coupontem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['coupontem:coupontem:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['coupontem:coupontem:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="coupontemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="优惠券类型" align="center" prop="couponType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_type" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" align="center" prop="couponAmout" >
        <template slot-scope="scope">
          <span>{{scope.row.couponAmout/100}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="满减金额" align="center" prop="fullAmount" /> -->
      <!-- <el-table-column label="发放开始时间" align="center" prop="grantStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.grantStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发放结束时间" align="center" prop="grantEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.grantEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="生效时间" align="center" prop="effectiveStartTime" width="180">
      </el-table-column>
      <el-table-column label="失效时间" align="center" prop="effectiveEndTime" width="180">
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
         <template slot-scope="scope">
          <dict-tag :options="dict.type.coupon_temp_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发放数量" align="center" prop="quantity" />
      <!-- <el-table-column label="每人可重复领取数量" align="center" prop="repeatQuantity" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['coupontem:coupontem:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['coupontem:coupontem:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="dialogIsCloseOnModal" :close-on-press-escape="dialogIsCloseOnModal">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
            <el-col :span="11">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" />
              </el-form-item>
            </el-col>
          <el-col :span="12">
            <el-form-item label="优惠券类型" prop="couponType">
                <el-select
                    v-model="form.couponType"
                    clearable
                    placeholder="请输入优惠券类型" 
                  >
                    <el-option
                      v-for="dict in dict.type.coupon_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
           </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="满减金额" prop="fullAmount">
              <el-input-number v-model="form.fullAmount" placeholder="请输入满减金额"  :min="0" :precision="2" controls-position="right"/>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="11">
            <el-form-item label="发放开始时间" prop="grantStartTime">
              <el-date-picker clearable
                v-model="form.grantStartTime"
                :picker-options="startPickerOptions"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发放开始时间"
                default-time="08:30:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放结束时间" prop="grantEndTime">
              <el-date-picker clearable
                v-model="form.grantEndTime"
                :picker-options="endPickerOptions"
                type="datetime"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择发放结束时间"
                default-time="17:30:00">
              </el-date-picker>
            </el-form-item>
          </el-col> -->
          <el-col :span="11">
            <el-form-item label="生效时间" prop="effectiveStartTime">
              <el-date-picker clearable
                v-model="form.effectiveStartTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择生效时间"
                :picker-options="startPickerOptions"
                default-time="08:30:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="effectiveEndTime">
              <el-date-picker clearable
                v-model="form.effectiveEndTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择失效时间"
                :picker-options="endPickerOptions"
                default-time="17:30:00">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="优惠金额" prop="couponAmout">
              <el-input-number v-model="form.couponAmout" placeholder="请输入优惠金额"  :min="0" :precision="2" controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放数量" prop="quantity">
              <el-input-number v-model="form.quantity" placeholder="请输入发放数量" :min="0"  controls-position="right"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="规则类型" prop="ruleType">
                <el-select
                    v-model="form.ruleType"
                    clearable
                    @change='ruleTypeSelect'
                    placeholder="请输入规则类型" 
                  >
                    <el-option
                      v-for="dict in dict.type.rule_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="Number(dict.value)"
                    />
                  </el-select>
                </el-form-item>
           </el-col>
           <el-col :span="12">
            <el-form-item label="门票" prop="tcouponTempReefAddDTOList">
                <el-select
                    v-model="form.tcouponTempReefAddDTOList"
                    clearable
                    @change='ticketSelect'
                    placeholder="请输入门票" 
                    multiple
                    value-key="refId"
                  >
                    <el-option
                      v-for="dict in ticketList"
                      :key="dict.refId"
                      :label="dict.refDesc"
                      :value="dict"
                    />
                  </el-select>
                </el-form-item>
           </el-col>
           <el-col :span="16">
            <el-form-item label="使用规则" prop="usageRules">
                <el-input
                    type="textarea"
                    :rows="4"
                    placeholder="请输入使用规则"
                    v-model="form.usageRules">
                  </el-input>
                </el-form-item>
           </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="每人可重复领取数量" prop="repeatQuantity">
              <el-input-number v-model="form.repeatQuantity" placeholder="请输入每人可重复领取数量" :min="0"  controls-position="right"/>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupontem, getCoupontem, delCoupontem, addCoupontem, updateCoupontem,getTicketListJQ,getTicketListHD } from "@/api/coupontem/coupontem";

export default {
  name: "Coupontem",
  dicts: ['coupon_type','rule_type','coupon_temp_status'],
  data() {
    return {
      // 门票List
      ticketList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券模板表格数据
      coupontemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        couponType: null,
        couponAmout: null,
        fullAmount: null,
        grantStartTime: null,
        grantEndTime: null,
        effectiveStartTime: null,
        effectiveEndTime: null,
        status: null,
        quantity: null,
        repeatQuantity: null
      },
      // 表单参数
      form: {
        tcouponTempReefAddDTOList: []
      },
      // 表单校验
      rules: {
        name:[
          { required: true, message: "请输入名称",trigger: "change",},
        ],
        effectiveStartTime:[
          { required: true, message: "请选择生效时间",trigger: "change",},
        ],
        effectiveEndTime:[
          { required: true, message: "请选择失效时间",trigger: "change",},
        ],
        couponAmout:[
          { required: true, message: "请输入优惠金额",trigger: "change",},
        ],
        quantity:[
          { required: true, message: "请输入发放数量",trigger: "change",},
        ],
        ruleType:[
          { required: true, message: "请选择规则类型",trigger: "change",},
        ],
        tcouponTempReefAddDTOList:[
          { required: true, message: "请选择门票",trigger: "change",},
        ],
        couponType:[
          { required: true, message: "请选择优惠券类型",trigger: "change",},
        ],
        usageRules:[
          { required: true, message: "请输入使用规则",trigger: "change",},
        ],
      },
      // 间隔天数
      optionalDate:0,
      startPickerOptions: {
        disabledDate: (time) => {
          let endTime = this.form.effectiveEndTime
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptions: {
        disabledDate: (time) => {
          let startTime = this.form.effectiveStartTime
          if (startTime) {
            const st = startTime.split(' ')[1];
            let dateTime = new Date(startTime);
            let startDateTime = dateTime.setDate(dateTime.getDate() - (st=='00:00:00'? 0: 1));
            // let endDateTime = dateTime.setDate(dateTime.getDate() + (st=='00:00:00'?this.optionalDate-1:this.optionalDate+1));
            
            return (
              time.getTime() < new Date(startDateTime).getTime() 
            );
          }
        }
      },
      startPickerOptionsQuery:{
        disabledDate: (time) => {
          let endTime = this.queryParams.effectiveEndTime
          if (endTime) {
            return time.getTime() > new Date(endTime).getTime()
          }
        }
      },
      endPickerOptionsQuery: {
        disabledDate: (time) => {
          let startTime = this.queryParams.effectiveStartTime
          if (startTime) {
            const st = startTime.split(' ')[1];
            let dateTime = new Date(startTime);
            let startDateTime = dateTime.setDate(dateTime.getDate() - (st=='00:00:00'? 0: 1));
            // let endDateTime = dateTime.setDate(dateTime.getDate() + (st=='00:00:00'?this.optionalDate-1:this.optionalDate+1));
            
            return (
              time.getTime() < new Date(startDateTime).getTime() 
            );
          }
        }
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    ruleTypeSelect(val,type){
      let temp=[]
      if(val){
        if(val==1){
          // 拿景区门票列表接口
          getTicketListJQ().then(res=>{
            res.data.map(item=>{
              temp.push({refId:item.scenicId,refDesc:item.scenicName})
            })
            this.ticketList=temp
          })    
        }else if(val==2){
          // 拿活动门票列表接口
          getTicketListHD().then(res=>{
            res.data.map(item=>{
              temp.push({refId:item.activityId,refDesc:item.activityName})
            })
            this.ticketList=temp
          })    
        }
      }else{
        this.ticketList=[]
      }
      if(type==1){

      }else{
        this.form.tcouponTempReefAddDTOList=[]
      }
    },
    // 选择门票
    ticketSelect(){

    },
    /** 查询优惠券模板列表 */
    getList() {
      this.loading = true;
      listCoupontem(this.queryParams).then(response => {
        this.coupontemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        couponType: null,
        couponAmout: 0,
        fullAmount: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDel: null,
        grantStartTime: null,
        grantEndTime: null,
        effectiveStartTime: null,
        effectiveEndTime: null,
        quantity: 0,
        ruleType: null,
        couponType: null,
        tcouponTempReefAddDTOList: [],
        usageRules:''
      };
      this.ticketList=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCoupontem(id).then(response => {
        this.form = response.data;
        this.form.couponAmout=response.data.couponAmout/100
        this.ruleTypeSelect(this.form.ruleType,1)
        console.log(this.form.tcouponTempReefAddDTOList)
        this.open = true;
        this.title = "修改优惠券模板";
      });
    },
    /** 提交按钮 */
    submitForm() {

      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupontem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupontem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const payIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除优惠券模板编号为"' + payIds + '"的数据项？').then(function() {
        return delCoupontem(payIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('coupontem/coupontem/export', {
        ...this.queryParams
      }, `coupontem_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-textarea__inner{
  font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
}
</style>
